package com.labot.service.impl;

import java.util.List;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.labot.dao.ConfigDao;
import com.labot.model.Config;
import com.labot.service.ConfigManager;
import com.labot.types.ConstantsGrupsType;
import com.labot.types.ConstantsType;


/**
 * Implementation of UserManager interface.
 * 
 * @author Ing. Enrique Barbeito.
 * 
 */
@Service("configManager")
@WebService(serviceName = "ConfigService", endpointInterface = "com.labot.service.ConfigService")
public class ConfigManagerImpl extends GenericManagerImpl<Config, Long> implements ConfigManager {

	private ConfigDao configDao;
	
	@Autowired
	public void setConfigDao(ConfigDao configDao) {
		 this.dao = configDao;
		 this.configDao = configDao;
	}

	@Override
	public List<Config> getConfigs(ConstantsGrupsType type) {
		return configDao.getConfigs(type);
	}
	
	@Override
	public List<Config> getAllConfigs() {
		return configDao.getAllConfigs();
	}

	public Config modifyConfig(Long id, String value) throws Exception {
		if (id==null) {
			throw new Exception("Null id?");
		}
		Config config = configDao.get(id);
		if (config == null) {
			throw new Exception("Error al conseguir Config.");
		}
		config.setValue(value);
		configDao.save(config);
		return config;
	}

	@Override
	@Transactional
	public Config createNewConfig(ConstantsType key) throws Exception {
		Config config = configDao.getConfig(key);
		if(config != null) {
			throw new Exception("La Constante ya existe");
		}
		config = new Config();
		config.setConstant(key);
		config.setValue(key.getDefaultValue());
		config.setConfigGroup(key.getGroup());
		configDao.saveConfig(config);
		return null;
	}

	@Override
	public Config getConfig(ConstantsType key) throws Exception {
		return configDao.getConfig(key);
	}
	

	@Override
	public void deprecateConstants() throws Exception {
		ConstantsType[] configs = ConstantsType.values();
		String values = "";
		for (ConstantsType constantsType : configs) {
			values = values + "," + "'" + constantsType + "'";
		}
		values = values.substring(1);
		String hql = "delete from Config where constant NOT IN ( " + values + " )";
		configDao.excuteBatch(hql);
		
	}
    
}
